<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%; overflow: auto; padding-bottom: 53px"
  >
    <template slot="title">
      <div style="width: 100%">
        <span>{{ title }}</span>
        <span style="display: inline-block; width: calc(100% - 51px); padding-right: 10px; text-align: right">
          <a-button @click="toggleScreen" icon="appstore" style="height: 20px; width: 20px; border: 0px"></a-button>
        </span>
      </div>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="form"
        :model="org"
        :rules="validatorRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        labelAlign="right"
      >
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="机构名称" prop="organizationName">
              <a-input
                style="width: 100%"
                placeholder="请输入机构名称"
                :max-length="10"
                v-model="org.organizationName"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="所在地区" prop="address">
              <a-cascader
                :options="options"
                :load-data="loadData"
                placeholder="请选择所在地区"
                change-on-select
                @change="onChange"
                v-model="address"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="机构等级">
              <a-select
                v-model="org.organizationLevel"
                placeholder="请选择机构等级"
                :getPopupContainer="target => target.parentNode"
              >
                <a-select-option :value="1">未指定</a-select-option>
                <a-select-option :value="2">三级甲等</a-select-option>
                <a-select-option :value="3">二级甲等</a-select-option>
                <a-select-option :value="4">一级甲等</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="联系电话">
              <a-input
                style="width: 100%"
                :max-length="20"
                placeholder="请输入联系电话"
                v-model="org.organizationPhone"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="机构地址" :labelCol="areaLabelCol" :wrapperCol="areaWrapperCol">
              <a-input v-model="org.organizationAddress" :max-length="30" placeholder="请输入机构地址" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="机构简介" :labelCol="areaLabelCol" :wrapperCol="areaWrapperCol">
              <a-textarea
                v-model="org.organizationIntroduce"
                :max-length="200"
                placeholder="请输入机构简介，200字以内"
                :auto-size="{ minRows: 5, maxRows: 8 }"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>

    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-button style="margin-right: 0.8rem" @click="handleCancel">取消</a-button>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { postAction, getAction } from '@/api/manage'
import moment from 'moment'

export default {
  name: 'OrgModal',
  components: {},
  props: ['isEdit'],
  data() {
    return {
      drawerWidth: 800,
      disableSubmit: false,
      provinceLoading: true,
      title: '操作',
      visible: false,
      org: {},
      address: [],
      options: [],
      imageUrl: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      areaLabelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      areaWrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      },
      uploadLoading: false,
      confirmLoading: false,
      validatorRules: {
        organizationName: [{ required: true, message: '请输入机构名称!' }],
        address: {
          type: 'array',
          required: true,
          validator: (rule, value, callback) => {
            if (this.address.length < 1) {
              callback(new Error('请选择所在地区'))
            } else {
              callback()
            }
          }
        }
      }
    }
  },
  watch: {
    address(n) {
      if (n.length < 3) return
      this.org.organizationProvinceId = n[0]
      this.org.organizationCityId = n[1]
      this.org.organizationAreaId = n[2]
    }
  },
  created() {
    this.getProvince()
  },
  methods: {
    async getLocation(record) {
      const index = this.locationFindIndex(record.organizationProvinceId, this.options)
      await this.loadData([this.options[index]])
      console.log(this.options[index])
      const index1 = this.locationFindIndex(record.organizationCityId, this.options[index].children)
      await this.loadData([this.options[index].children[index1]])
      this.address = [+record.organizationProvinceId, +record.organizationCityId, +record.organizationAreaId]
      console.log(this.address)
    },
    async getDetail(id, orgCode) {
      const res = await getAction('org/get', { id, orgCode })
      if (res.success) {
        this.org = res.result
        const index = this.locationFindIndex(res.result.organizationProvinceId, this.options)
        await this.loadData([this.options[index]])
        const index1 = this.locationFindIndex(res.result.organizationCityId, this.options[index].children)
        await this.loadData([this.options[index].children[index1]])
        this.address = [
          +res.result.organizationProvinceId,
          +res.result.organizationCityId,
          +res.result.organizationAreaId
        ]
      } else {
        console.log(res.message)
      }
    },
    locationFindIndex(value, arr) {
      return arr.findIndex(v => {
        return v.value == value
      })
    },
    add() {
      this.edit()
      console.log(this.address)
    },
    edit(record) {
      this.visible = true
      record && this.getDetail(record.dataId, record.organizationCode)
      this.resetScreenSize()
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth
      } else {
        this.drawerWidth = 800
      }
    },
    //窗口最大化切换
    toggleScreen() {
      if (this.modaltoggleFlag) {
        this.modalWidth = window.innerWidth
      } else {
        this.modalWidth = 800
      }
      this.modaltoggleFlag = !this.modaltoggleFlag
    },
    getProvince() {
      getAction('/dict/district/province')
        .then(res => {
          if (res.success) {
            this.options = res.result.map(v => {
              return {
                value: v.districtId,
                label: v.name,
                isLeaf: false,
                level: 1
              }
            })
          }
        })
        .finally(_ => {
          this.provinceLoading = false
        })
    },
    handleSubmit() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          postAction('org/edit', this.org).then(res => {
            if (res.success) {
              that.$message.success('操作成功')
              this.$emit('ok')
              this.handleCancel()
            }
          })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.confirmLoading = false
      this.visible = false
      this.disableSubmit = false
      this.$refs.form.resetFields()
      this.org = {}
      this.address = []
      this.$emit('cancel', false)
    },
    onChangeAddress() {},
    async getAreaData(id) {
      let result
      await getAction('dict/district/city', { provinceId: id }).then(res => {
        if (res.success) {
          result = res.result
        } else {
          console.log(res.message)
        }
      })
      return result
    },
    async loadData(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      const area = []
      const address = await this.getAreaData(selectedOptions[selectedOptions.length - 1].value)
      await Promise.all(
        address.map(v => {
          area.push({
            value: v.districtId,
            label: v.name,
            isLeaf: targetOption.level == 2 ? true : false
          })
        })
      )
      targetOption.children = area.map(v => {
        return {
          ...v,
          level: targetOption.level == 1 ? 2 : 3
        }
      })
      this.options = [...this.options]
    },
    onChange() {},
    disabledDate(current) {
      return current > moment().endOf('day')
    }
  }
}
</script>

<style lang="less" scoped>
.avatar {
  display: block;
  margin: 50px auto;
}
/deep/.ant-upload {
  display: block;
  text-align: center;
}
/deep/.ant-col-sm-4 {
  width: 14.67%;
}
/deep/.ant-col-sm-19 {
  width: 81.17%;
}
.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>

